package cn.ijero.waterfallflow;

import android.os.Bundle;
import android.util.Log;

import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import cn.ijero.waterfallflow.data.FlowData;
import cn.ijero.waterfallflow.detial.DetailActivity;

public class MainActivity extends BaseActivity {
    private ListAdapter listAdapter;
    private RecyclerView recyclerView;
    private SmartRefreshLayout smartRefreshLayout;
    private MainViewModel viewModel;
    private int page = 0;

    @Override
    protected void initViewBefore(Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(this).get(MainViewModel.class);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.addItemDecoration(new SpaceItemDecoration());
        listAdapter = new ListAdapter();
        recyclerView.setAdapter(listAdapter);

        smartRefreshLayout = findViewById(R.id.smartRefreshLayout);
    }

    @Override
    protected void initViewListener() {
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            // 刷新
            page = 0;
            viewModel.loadData(page);
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            // 加载更多
            viewModel.loadData(page);
        });
        listAdapter.setOnItemClickListener((adapter, view, position) -> {
            FlowData.Data data = (FlowData.Data) adapter.getData().get(position);
            DetailActivity.start(this, data.getFromPageTitleEnc(), data.getMiddleURL());
        });
    }

    @Override
    protected void initObserver() {
        viewModel.liveData.observe(this, list -> {
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.finishLoadMore();
            if (page == 0) {
                listAdapter.setList(list);
            } else {
                listAdapter.addData(list);
            }
            if (list.size() < 30) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData();
                return;
            }
            page++;
            Log.d("MainActivity", "onCreate: page=" + page);
        });
    }

    @Override
    protected void initData() {
        viewModel.loadData(page);
    }

}